package com.inspector.app.ui.login

import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.example.commen.base.BaseActivity
import com.example.commen.manager.ActivityManager
import com.example.commen.resource.CommentContect
import com.example.commen.utile.CommonStringUtils
import com.example.commen.utile.CommonUtils.getColor
import com.hjq.http.listener.HttpCallback
import com.hjq.toast.Toaster
import com.inspector.app.databinding.FragmentPhoneNumLoginBinding
import com.inspector.app.di.network.api.SmsloginApi
import com.inspector.app.di.network.api.UserInfoApi
import com.inspector.app.ui.base.BaseDJFragment
import com.inspector.app.ui.main.MainActivity

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

/**
 * A simple [Fragment] subclass.
 * Use the [PhoneNumLoginFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class PhoneNumLoginFragment : BaseDJFragment<FragmentPhoneNumLoginBinding>() {
    private val viewModel: LoginModel by activityViewModels()
    private val isRePassword = false

    override fun provideViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentPhoneNumLoginBinding {
        return FragmentPhoneNumLoginBinding.inflate(inflater, container, false)
    }

    override fun setupView(view: View, savedInstanceState: Bundle?) {

    }


    val time = 60
    var timedown = time
    var countDownTimer: CountDownTimer? = object : CountDownTimer((time * 1000).toLong(), 1000) {

        override fun onTick(l: Long) {
            viewBinding.tvDialogLoginGetyzm.isEnabled = false
            viewBinding.tvDialogLoginGetyzm.setTextColor(
                ResourcesCompat.getColor(
                    resources,
                    com.example.commen.R.color.gray,
                    null
                )
            )
            viewBinding.tvDialogLoginGetyzm.text = timedown.toString() + "s"
            timedown--
        }

        override fun onFinish() {
            initBtGetYZM()
        }
    }

    override fun initData() {
        //设置其大小
        if (isRePassword) {
            setInitRePasswordView()
        }

    }

    override fun initListener() {
        ClickUtils.applyGlobalDebouncing(
            viewBinding.tvDialogLoginGetyzm,
            CommentContect.config.clickDelayTime
        ) { v ->
            val msg = viewBinding.edtLoginName.text.toString()
            if (msg.isEmpty()) {
                Toaster.show(this.getString(com.example.commen.R.string.common_phone_input_hint))
                return@applyGlobalDebouncing
            }
            if (!CommonStringUtils.isPhoneNumber(msg)) {
                Toaster.show(this.getString(com.example.commen.R.string.common_phone_input_error))
                return@applyGlobalDebouncing
            }
            countDownTimer?.start()
            viewModel.getAuthCode(
                this,
                viewBinding.edtLoginName.text.toString(),
                object : HttpCallback<SmsloginApi.loginResult>(this) {
                    override fun onSucceed(result: SmsloginApi.loginResult) {
                        if (result.code == 200) {
                            Toaster.show(getString(com.example.commen.R.string.common_code_send_hint))
                        } else {
                            Toaster.show(result.message)
                        }
                    }

                    override fun onFail(e: Exception) {
                        countDownTimer?.cancel()
                        initBtGetYZM()
                        Toaster.show(e.message)
                    }
                })
        }
        ClickUtils.applyGlobalDebouncing(
            viewBinding.btLoginGo,
            CommentContect.config.clickDelayTime
        ) { v ->
            val name = viewBinding.edtLoginName.text.toString()
            val pwd = viewBinding.edtLoginPwd.text.toString()
            if (!CommonStringUtils.isPhoneNumber(name)) {
                Toaster.show(this.getString(com.example.commen.R.string.common_phone_input_error))
                return@applyGlobalDebouncing
            }
            if (pwd.isEmpty()) {
                Toaster.show(this.getString(com.example.commen.R.string.common_code_input_hint))
                return@applyGlobalDebouncing
            }
            viewModel.smsLogin(
                this,
                name,
                pwd,
                object : HttpCallback<SmsloginApi.loginResult>(this) {
                    override fun onSucceed(result: SmsloginApi.loginResult) {
                        viewModel.getUserInfo(this@PhoneNumLoginFragment,
                            object : HttpCallback<UserInfoApi.UserInfo>(this) {
                                override fun onSucceed(result: UserInfoApi.UserInfo) {
                                    Toaster.show("登录成功")
                                    goToActivity(requireActivity(), MainActivity::class.java)
                                    ActivityManager.getInstance()
                                        .finishAllActivities(MainActivity::class.java)
                                }

                                override fun onFail(e: java.lang.Exception) {
                                    Toaster.show(e.localizedMessage)
                                }
                            })
                    }

                    override fun onFail(e: Exception) {
                        Toaster.show(e.localizedMessage)
                    }
                })
        }

    }

    private fun initBtGetYZM() {
        viewBinding.tvDialogLoginGetyzm.setTextColor(getColor(com.example.commen.R.color.material_blue_500))
        viewBinding.tvDialogLoginGetyzm.text =
            getString(com.example.commen.R.string.common_code_send)
        viewBinding.tvDialogLoginGetyzm.isEnabled = true
        timedown = time
    }

    private fun setInitRePasswordView() {
        viewBinding.edtLoginName.setText(CommentContect.loginNameCache)
        viewBinding.edtLoginName.isClickable = false
        viewBinding.edtLoginName.isFocusable = false
    }


    override fun onDestroy() {
        countDownTimer?.cancel()
        countDownTimer = null
        KeyboardUtils.unregisterSoftInputChangedListener(activity?.window!!)
        super.onDestroy()
    }
}